setwd("C:/Users/jscho/Documents/Migration Research-- David Leblang & Justin Schon")

library(tidyverse)
library(foreign)
library(readstata13)
library(cshapes)
library(countrycode)

destination<- read.dta13("year_destination_collapsed.dta")
destination<- subset(destination, destination$year==2016)       

destination.Avdan<- destination %>%
  select(state1no,Avdan_barrier) %>%
  mutate(
    Avdan.binary = ifelse(Avdan_barrier>=1,1,0)
  )

destination.Avdan$cow<- countrycode(destination.Avdan$state1no,"iso3n","cown")

destination.Hassner<- destination %>%
  select(state1no,Hassner_barrier) %>%
  mutate(
    Hassner.binary = ifelse(Hassner_barrier>=1,1,0)
  )

destination.Poast<- destination %>%
  select(state1no,Poast_barrier) %>%
  mutate(
    Poast.binary = ifelse(Poast_barrier>=1,1,0)
  )


cmap.2012.Avdan<- cshp(date=as.Date("2012-1-1"))
cmap.2012.Avdan<- merge(cmap.2012.Avdan,destination.Avdan,by.x="COWCODE",by.y="state1no")
cmap.2012.Avdan.sub <- subset(cmap.2012.Avdan, !is.na(COWCODE))

cmap.2012.Hassner<- cshp(date=as.Date("2012-1-1"),useGW = F)
cmap.2012.Hassner<- merge(cmap.2012.Hassner,destination.Hassner,by.x="COWCODE",by.y="state1no")
cmap.2012.Hassner.sub <- subset(cmap.2012.Hassner, !is.na(COWCODE))

cmap.2012.Poast<- cshp(date=as.Date("2012-1-1"))
cmap.2012.Poast<- merge(cmap.2012.Poast,destination.Poast,by.x="COWCODE",by.y="state1no")
cmap.2012.Poast.sub <- subset(cmap.2012.Poast, !is.na(COWCODE))

#Plots are not working, so switching to ArcMap
library(rgdal)
writeOGR(cmap.2012.Poast.sub,dsn = getwd(), layer = "P&C_2016", driver="ESRI Shapefile")


my.palette <- c("red","blue")

cmap.2012.Avdan.sub@data$Avdan.binary<- as.factor(cmap.2012.Avdan.sub@data$Avdan.binary)

spplot(cmap.2012.Avdan.sub,"Avdan.binary", col.regions=my.palette,
       sp.layout=cmap.2012.Avdan,
       main="Avdan & Gelpi Barriers, 2013")

cmap.2012.Hassner.sub@data$Hassner.binary<- as.factor(cmap.2012.Hassner.sub@data$Hassner.binary)

spplot(cmap.2012.Hassner.sub, "Hassner.binary",col.regions=my.palette,
       sp.layout=cmap.2012.Hassner,
       main="Hassner & Wittenberg Barriers, 2014")

cmap.2012.Poast.sub@data$Poast.binary<- as.factor(cmap.2012.Poast.sub@data$Poast.binary)

spplot(cmap.2012.Poast.sub,"Poast.binary", col.regions=my.palette,
       sp.layout=cmap.2012.Poast,
       main="Poast & Carter Barriers, 2014")




